package com.magnate.software.thrift.service;

import com.magnate.software.thrift.api.service.UserService;
import com.magnate.software.thrift.service.proxy.ThriftServletProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.servlet.Servlet;

/**
 * 启动类
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2016/12/9 15:37
 */
@SpringBootApplication
@EnableTransactionManagement
public class StartUpApplication {

    private Logger logger = LoggerFactory.getLogger(StartUpApplication.class);

    public static void main(String[] args) {

        SpringApplication app = new SpringApplication(StartUpApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);

        //new SpringApplicationBuilder(StartUpApplication.class).bannerMode(Banner.Mode.OFF).run(args);
    }

    /**
     * 每个接口都创建一个ThriftServletProxy实例
     *
     * @param iface
     * @param impl
     * @return
     * @throws Exception
     */
    private ThriftServletProxy servletProxy(String iface, Object impl) throws Exception {
        ThriftServletProxy rtn = new ThriftServletProxy(iface, impl);
        logger.info("============servletProxy: " + rtn.hashCode());
        return rtn;
    }

    @Bean
    public ServletRegistrationBean userBean(UserService.Iface impl) throws Exception {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        logger.info("============ userBean begin =========");
        Servlet proxy = servletProxy("com.magnate.software.thrift.api.service.UserService", impl);
        logger.info("============ userBean end =========");
        reg.setServlet(proxy);
        reg.addUrlMappings("/api/user");
        reg.setName("userService");
        return reg;
    }
}
